from faker import Faker
import random
from datetime import datetime, timedelta
from data_mock.utils import MysqlUtils_AI

fake = Faker('zh_CN')

# ========== 癌症类型配置 ==========
CANCER_TYPES = {
    'C34.90': {'name': '肺恶性肿瘤', 'symptoms': ['咳嗽', '咯血', '胸痛', '呼吸困难'], 'treatments': ['放疗', '化疗', '靶向治疗']},
    'C16.9': {'name': '胃恶性肿瘤', 'symptoms': ['上腹痛', '恶心呕吐', '黑便', '食欲减退'], 'treatments': ['胃切除术', '化疗']},
    'C18.9': {'name': '结肠恶性肿瘤', 'symptoms': ['腹痛', '便血', '排便习惯改变', '体重下降'], 'treatments': ['结肠切除术', '辅助化疗']},
    'C50.919': {'name': '乳腺恶性肿瘤', 'symptoms': ['乳房肿块', '乳头溢液', '皮肤凹陷', '腋窝淋巴结肿大'], 'treatments': ['改良根治术', '内分泌治疗', '放化疗']},
    'C61': {'name': '前列腺恶性肿瘤', 'symptoms': ['排尿困难', '尿频', '血尿', '骨盆疼痛'], 'treatments': ['雄激素剥夺治疗', '放疗', '手术切除']}
}


# ========== 生成主函数 ==========
def generate_progress_records():
    sql_statements = []
    record_sn_counter = 60001

    for day in generate_day_range("2025-08-01", "2025-08-30"):
        # 每天生成随机数量的病程记录（每位患者可能有多次记录）
        records_per_day = random.randint(5, 10)

        for i in range(records_per_day):
            cancer_code, cancer_info = random.choice(list(CANCER_TYPES.items()))
            patient_id = f"PT{random.randint(1000, 9999)}"
            visit_sn = f"VIS{random.randint(1000, 9999)}"
            record_sn = f"PROG{record_sn_counter}"
            record_sn_counter += 1

            # 随机选择病程类型
            record_title = random.choice(["首次病程记录", "日常病程记录", "上级医师查房记录", "阶段小结", "出院前病程记录"])

            # 构造病程记录内容
            record_content = generate_progress_note(cancer_info, record_title)

            data = {
                'patient_id': patient_id,
                'visit_sn': visit_sn,
                'medical_record_no': f"MR{random.randint(100000, 999999)}",
                'inpatient_no': f"IP{random.randint(100000, 999999)}",
                'hospitalization_times': str(random.randint(1, 5)),
                'record_sn': record_sn,
                'record_datetime': fake.date_time_between(
                    start_date=datetime.strptime(day, "%Y-%m-%d"),
                    end_date=datetime.strptime(day, "%Y-%m-%d") + timedelta(days=1)
                ).strftime('%Y-%m-%d %H:%M:%S'),
                'record_title': record_title,
                'record_content': record_content,

                # 系统字段
                'record_status': 1,
                'yy_upload_status': 0,
                'yy_etl_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'yy_batch_time': day,
                'yy_record_batch_id': f"BATCH{day}_{i}"
            }

            sql = generate_sql('b06_1', data)
            sql_statements.append(sql)

    return sql_statements


# ========== 病程文书内容生成 ==========
def generate_progress_note(cancer_info, record_title):
    """根据癌症类型与病程阶段生成文书内容"""
    name = cancer_info['name']
    symptom = random.choice(cancer_info['symptoms'])
    treatment = random.choice(cancer_info['treatments'])
    condition_trend = random.choice(["病情稳定", "病情好转", "病情加重", "出现并发症"])

    # 不同病程类型的模板
    if "首次" in record_title:
        return f"患者入院后精神可，食欲一般，诉{symptom}。已完善相关检查，初步考虑{name}。拟行{treatment}治疗计划。"
    elif "日常" in record_title:
        return f"患者目前一般情况尚可，{symptom}较前减轻，继续给予{treatment}，病情{condition_trend}。"
    elif "查房" in record_title:
        return f"上级医师查房：患者{name}诊断明确，检查结果复核无误，调整治疗方案为：继续{treatment}，加强营养支持。"
    elif "阶段" in record_title:
        return f"阶段小结：患者自入院以来，接受{treatment}共{random.randint(1,5)}个疗程，病情总体{condition_trend}。"
    elif "出院前" in record_title:
        return f"患者出院前评估：一般情况良好，{symptom}明显改善，{treatment}取得初步疗效，建议门诊随访。"
    else:
        return f"患者病情记录：{symptom}症状持续存在，{treatment}中，病情{condition_trend}。"


# ========== 辅助函数 ==========
def generate_day_range(start_date, end_date):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")
    delta = end - start
    return [(start + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(delta.days + 1)]


def generate_sql(table, data):
    columns = []
    values = []
    for k, v in data.items():
        columns.append(f"`{k}`")
        if v is None:
            values.append("NULL")
        elif isinstance(v, (int, float)):
            values.append(str(v))
        else:
            escaped_value = str(v).replace("'", "''")
            values.append(f"'{escaped_value}'")
    return f"INSERT INTO `{table}` ({', '.join(columns)}) VALUES ({', '.join(values)});"


# ========== 执行生成 ==========
if __name__ == "__main__":
    print("开始生成病程记录数据...")
    records = generate_progress_records()
    MysqlUtils_AI.insert_data_to_hub(records, 'b06_1')
    print(f"已生成 {len(records)} 条 b06_1 病程记录数据。")
